<script setup lang="ts">
import {throwError} from '~/utils/throwError'
import request from '~/utils/request'
import {SUCCESS_CODE} from '~/common/constants'
import {useSystemStore} from '~/store/system'

const nuxtApp = useNuxtApp()
const systemStore = useSystemStore()

const page = ref(1)
const loadFinished = ref(false)
const currentTab = ref('articles')

/**
 * 加载咨询相关数据
 */
const newsDataList =ref([])
const fetchIndexNews = async (server: boolean) => {
  if (!loadFinished.value) {
    try {
      const res = await request(`/index/news?page=${page.value}&limit=6`, {
        METHOD: 'GET',
        server,
        key: 'fetchIndexNews'
      })
      const {code, data} = res.data.value
      if (SUCCESS_CODE === code) {
        if (data.length) {
          newsDataList.value.push(...data)
        } else {
          if (currentTab.value === 'news') {
            loadFinished.value = true
          }
        }
      }
    } catch (e) {
      if (server) {
        throwError(e.message)
      } else {
        nuxtApp.$mutual.message.error(e.message)
      }
    } finally {
      if (!systemStore.indexNewsDataLoaded) {
        // 只需要加载一次就证明首屏数据已成功加载，后续不再改变此标识以防止到底部加载时数据加载后页面也跟着刷新
        systemStore.indexNewsDataLoaded = true
      }
    }
  }
}

/**
 * 加载文章相关数据
 */
const articleDataList = ref([])
const fetchIndexArticles = async (server: boolean,categoryId = 0) => {
  if (!loadFinished.value) {
    try {
      const res = await request(`/index/article?page=${page.value}&limit=6&categoryId=${categoryId}`, {
        METHOD: 'GET',
        server,
        key: 'fetchIndexArticles'
      })
      const {code, data} = res.data.value
      if (SUCCESS_CODE === code) {
        if (data.length) {
          articleDataList.value.push(...data)
        } else {
          if (currentTab.value === 'articles') {
            loadFinished.value = true
          }
        }
      }
    } catch (e) {
      if (server) {
        throwError(e.message)
      } else {
        nuxtApp.$mutual.message.error(e.message)
      }
    } finally {
      if (!systemStore.indexArticlesDataLoaded) {
        // 只需要加载一次就证明首屏数据已成功加载，后续不再改变此标识以防止到底部加载时数据加载后页面也跟着刷新
        systemStore.indexArticlesDataLoaded = true
      }
    }
  }
}

if (systemStore.currentCategoryId === 0) {
  currentTab.value = 'news'
  fetchIndexNews(true)
}
fetchIndexArticles( true,systemStore.currentCategoryId)

const resetData = (tab) => {
  page.value = 1
  currentTab.value = tab
  loadFinished.value = false
  systemStore.indexArticlesDataLoaded = false
  systemStore.indexNewsDataLoaded = false
  newsDataList.value.length = 0
  articleDataList.value.length = 0
}

const onTabChange = (tab) => {
  resetData(tab)
  if (tab === 'articles') {
    fetchIndexArticles(false,systemStore.currentCategoryId)
  } else {
    fetchIndexNews(false)
  }
}

watch(() => systemStore.reachBottom, (isBottom) => {
  if (isBottom) {
    if (!loadFinished.value) {
      let pageVal = page.value
      page.value = ++pageVal
      if (currentTab.value === 'articles') {
        fetchIndexArticles(false, systemStore.currentCategoryId)
      } else {
        fetchIndexNews(false)
      }
    }
  }
})

watch(() => systemStore.indexNewsDataLoaded, (value) => {
  if (value) {
    setTimeout(() => systemStore.homePageImageLazyLoad(), 20)
  }
}, {
  immediate: true
})

watch(() => systemStore.indexArticlesDataLoaded, (value) => {
  if (value) {
    setTimeout(() => systemStore.homePageImageLazyLoad(), 20)
  }
}, {
  immediate: true
})

watch(() => systemStore.currentCategoryId, () => resetData(currentTab.value), {
  immediate: true
})
</script>

<template>
  <IndexCategoryContent :news-data-list="newsDataList" :article-data-list="articleDataList" @tab-change="onTabChange"/>
</template>
